<template>
  <div>
    <Modal
      :value="modalState"
      :title="title"
      :loading="loading"
      @on-ok="handleSubmit"
      @on-cancel="cancel"
      width="600">
      <Form
        ref="departmentModal"
        :model="row"
        :rules="ruleInline"
        inline
        style="width: 100%"
        :label-width="85">
        <FormItem prop="name" label="部门名" style="width: 250px">
          <Input type="text" v-model="row.name" placeholder="请输入部门名" />
        </FormItem>
        <FormItem v-show="row.id" prop="state" label="状态" style="width: 250px">
          <Select v-model="row.state" clearable placeholder="请选择状态">
            <Option value="0">
              正常
            </Option>
            <Option value="1">
              禁用
            </Option>
          </Select>
        </FormItem>
        <FormItem prop="des" label="部门描述" style="width: 100%">
          <Input v-model="row.des" type="textarea" placeholder="请输入部门描述" />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import {
  mapActions,
  mapState
} from 'vuex'
export default {
  name: 'DepartmentModal',
  data () {
    return {
      title: '',
      loading: true,
      form: {
        name: '',
        state: '',
        des: ''
      },
      ruleInline: {
        name: [
          { required: true, message: '部门名不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  updated () {
    if (this.row.id && this.row.id !== '') {
      this.title = '修改部门信息'
    } else {
      this.title = '添加部门记录'
    }
  },
  computed: {
    ...mapState({
      row: state => state.department.row,
      modalState: state => state.modal.modalState
    })
  },
  methods: {
    ...mapActions(['updateModalState']),
    changeLoading () {
      this.loading = false
      this.$nextTick(() => {
        this.loading = true
      })
    },
    handleSubmit () {
      this.$refs.departmentModal.validate((valid) => {
        if (!valid) {
          return this.changeLoading()
        }
        this.$emit('department-valid', {
          id: this.row.id,
          name: this.row.name,
          state: this.row.state ? parseInt(this.row.state) : '',
          des: this.row.des
        })
        this.$refs['departmentModal'].resetFields()
      })
    },
    cancel () {
      this.updateModalState(false)
      this.$refs['departmentModal'].resetFields()
    }
  }
}
</script>
